//
//  LoginViewController.swift
//  ManBetX
//
//  Created by Cocoa on 2020/4/4.
//  Copyright © 2020 Fullen. All rights reserved.
//

import UIKit

import Eagleeyes.DevicePrint
import Lottie
/**
 * 登录页 Controller
 */

// 登录成功回调
typealias LoginSucceedBlock = () -> Void

class LoginViewController: BaseViewController,UITextFieldDelegate {

    // 登录 - IBOutlet
    @IBOutlet weak var accountTextField: UITextField!// 账号输入框
    @IBOutlet weak var passwordTextField: UITextField!// 密码输入框
    @IBOutlet weak var loginShowHidePassword: UIButton!// 显示密码
    @IBOutlet weak var savePasswordButton: UIButton!// 记住密码
    @IBOutlet weak var loginForgetPassword: UIButton!// 忘记密码显示
    @IBOutlet weak var loginButton: UIButton!// 登录
    @IBOutlet weak var switchoverButton: UIButton!// 先去逛逛->跳至主页面
    @IBOutlet weak var switchToRegisterButton: UIButton!// 立即注册->跳至注册页
    
    var loginSucceedBlock: LoginSucceedBlock?
    // 登录、注册 - property

    var codeString = ""
    var sessionid = ""

    let codepophelp =  PopWindowHelper()
    var shouldCheckUpdate = true
    var shouldNotEmptyPasswordField = false
    var domainNum: Int = 0;
    
    var locationBlocked: Bool = false
    var adViewController: GuidePageController?
    
    var checkingUpdate: Bool = false
    var firstload = true
    var outAppAC : UIAlertController!
    
    override var prefersStatusBarHidden: Bool {
        return self.isStatusBarHidden
    }
    
    var isStatusBarHidden = false {
        
        didSet{
            self.setNeedsStatusBarAppearanceUpdate()
        }
    }
        
// MARK: -- class func
    class func loginIfNeedController(currentController: UIViewController,succeedBlock: @escaping LoginSucceedBlock) {
        
        if UserHelper.getLoginStatus() == false {
            let loginViewController = LoginViewController.instanceFromStoryboard()!
            let naviLoginViewController = UINavigationController(rootViewController: loginViewController)
            loginViewController.loginSucceedBlock = succeedBlock
            currentController.present(naviLoginViewController, animated: true, completion: nil)
        }else {
            succeedBlock()
        }
                //4. 调用闭包,设置你想传递的参数,调用前先判定一下,是否已实现
        //        if succeedBlock != nil {
        //            succeedBlock!()
        //        }
                
        
        
    }
    
// MARK: -- life cycle
        
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configureUI()
        addNotification()
        RequestHelper.deleteDefaultCookie()// 删除默认 Cookie
        RequestHelper.makeCFCookie()
        LoginDataProvider.getEncrypted(succeedBlock: { (modulus, exponent) in}) {}
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        addGradientLayer()
        // 设置导航栏隐藏
        self.navigationController?.setNavigationBarHidden(true, animated:true)

        self.isStatusBarHidden = true
        if(isTest){
            UserDefaults.standard.set("", forKey: DefaultKey.VCTOKEN81)
            UserDefaults.standard.set("", forKey: DefaultKey.CCTOKEN81)
        }else{
            UserDefaults.standard.set("", forKey: DefaultKey.VCTOKEN11)
            UserDefaults.standard.set("", forKey: DefaultKey.CCTOKEN11)
        }
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        let defaults = UserDefaults.standard
        //发送一个通知 或者 传递值 来跳转
        
        if let defaultUsername = defaults.value(forKey: DefaultKey.USER_LOGIN_NAME) {
            if let username = defaultUsername as? String {
                if username != accountTextField.text! {
                    self.accountTextField.text = username
                    
                    if shouldNotEmptyPasswordField {
                        shouldNotEmptyPasswordField = false
                    }else{
                        self.passwordTextField.text = ""
                    }
                    
                    defaults.set(false, forKey: DefaultKey.USER_IS_AUTO_LOGIN)
                    defaults.set(false, forKey: DefaultKey.USER_IS_SAVE_PASSWORD)
                    defaults.set(nil, forKey: DefaultKey.USER_LOGIN_PASSWORD)
                }
            }
        }
    }
    
    deinit {
        // 移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
// MARK: -- func

    func configureUI() {
        self.view.backgroundColor = UIColor.white
        self.setNeedsStatusBarAppearanceUpdate()
        
        // 填写缓存账号密码
        let defaults = UserDefaults.standard
        if let username = defaults.value(forKey: DefaultKey.USER_LOGIN_NAME) {
            self.accountTextField.text = username as? String
        }
        if let isSavePassword = defaults.value(forKey: DefaultKey.USER_IS_SAVE_PASSWORD) as? Bool {
            if isSavePassword == true {
                if let password = defaults.value(forKey: DefaultKey.USER_LOGIN_PASSWORD) {
                    self.passwordTextField.text = password as? String
                }
                self.savePasswordButton.isSelected = true
            }
        }
    }
    
    // 添加通知
    func addNotification() {
        // 输入框通知
        NotificationCenter.default.addObserver(self, selector: #selector(textFiledEditChanged(textField:)), name: UITextField.textDidChangeNotification, object: nil)
    }
    
    func addGradientLayer() {
        // 注意：需要控件创建frame布局后，渐变色layer才能加。否则会显示异常
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.loginButton.bounds
        gradientLayer.colors = [
            UIColor.init("FF914A")!.cgColor,
            UIColor.init("FBCE81")!.cgColor
        ]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0)
        self.loginButton.layer.insertSublayer(gradientLayer, at: 0)
    }
    
    
// MARK: -- @objc func
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
    }
    
    @objc func textFiledEditChanged(textField: UITextField) {
        if self.accountTextField.isFirstResponder {
            print("accountTextField:\(self.accountTextField.text!)")
        }else if self.passwordTextField.isFirstResponder {
            print("passwordTextField:\(self.passwordTextField.text!)")
        }
    }
    
// MARK: -- @IBAction func
    
    // 关闭登录页
    @IBAction func dismissClick(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }
    
    // 显示密码
    @IBAction func loginShowPasswordClick(_ sender: UIButton) {
        
        sender.isSelected = !sender.isSelected
        self.passwordTextField.isSecureTextEntry = !self.passwordTextField.isSecureTextEntry

        ToolHelper.statisticsPage(pageName: "登录/注册-密码-显示密码")
        print("loginShowPassword")
    }
    
    //忘记密码
    @IBAction func loginForgetPasswordClick(_ sender: Any) {
        self.navigationController?.pushViewController(ForgetPassWordViewController(), animated: true)
    }
    
    // 记住密码 - isSelected
    @IBAction func loginRememberPasswordClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        ToolHelper.statisticsPage(pageName: "登录/注册-登录栏-记住密码")
    }
    
    // 登录按钮点击
    @IBAction func loginRegistertClick(_ sender: UIButton) {
        self.loginFunc()
    }
    // 先去逛逛、已有万博账号
    @IBAction func switchoverClick(_ sender: UIButton) {
        ToolHelper.statisticsPage(pageName: "登录/注册-登录页-暂不登录")
        self.dismiss(animated: true, completion: nil)
    }
    // 立即注册
    @IBAction func switchToRegisterClick(_ sender: UIButton) {
        let registerViewController = RegisterViewController.instanceFromStoryboard()!
        self.navigationController?.pushViewController(registerViewController, animated: true)
    }
    
    // 登录功能
    func loginFunc(){
        self.view.endEditing(true)
        ToolHelper.statisticsPage(pageName: "登录/注册-登录页-登录")
        if self.accountTextField.text?.count ?? 0 <= 0{
             UIHelper.alertSimpleMessage(about: "请填写会员账号", withDescription: "", in: self)
                return
        }
        if self.passwordTextField.text?.count ?? 0 <= 0{
            UIHelper.alertSimpleMessage(about: "请填写会员密码", withDescription: "", in: self)
            return
        }
        
        if let username = self.accountTextField.text {
            if let password = self.passwordTextField.text {
                self._loadView = UIHelper.initLoadView(self, withMessage: "读取中...")
                self.view.addSubview(self._loadView!)
               let isSignKeyStatus = UserDefaults.standard.bool(forKey: DefaultKey.IS_SIGNKEY_STATUS)
                if isSignKeyStatus == true{
                    self.actionLogin(username: username, password: password)
                }else{
                    self.getSignKey(username: username, password: username)
                }
            }
        }
    }

    // 调用网络登录前的处理
//    func actionLogin(username: String?, password: String?){
//        let isIpStatus = UserDefaults.standard.bool(forKey: DefaultKey.IS_IP_STATUS)
//        if isIpStatus == true{ //是否已在启动页获取到域名
//            let modulus = UserDefaults.standard.value(forKey: DefaultKey.MODULUS)
//            let exponent = UserDefaults.standard.value(forKey: DefaultKey.EXPONENT)
//            if modulus == nil || exponent == nil {
//                self.getKeyAndLogin2App(username: username ?? "", password: password ?? "")
//            }else{
//                let encryptedPassword = RSAHelper.encrypt(password ?? "", modulus: modulus as? String ?? "", exponent: exponent as? String ?? "")
//                self.login2App(username: username ?? "", password: password ?? "", encryptedPassword:encryptedPassword!)
//            }
//        }else{//之前获取 DoMainIp 失败 - 再次尝试
//            AppDataConfigure.getDoMainIp(succeedBlock: { (dic) in
//                let encryptedPassword = RSAHelper.encrypt(password, modulus: dic?["modulus"] ?? "", exponent: dic?["exponent"] ?? "")
//                self.login2App(username: username ?? "", password: password ?? "", encryptedPassword:encryptedPassword!)
//            })
//        }
//    }
    
    // 调用网络登录前的处理
    func actionLogin(username: String?, password: String?){
        let modulus = UserDefaults.standard.value(forKey: DefaultKey.MODULUS)
        let exponent = UserDefaults.standard.value(forKey: DefaultKey.EXPONENT)
        if modulus != nil,exponent != nil {
            let encryptedPassword = RSAHelper.encrypt(password ?? "", modulus: modulus as? String ?? "", exponent: exponent as? String ?? "")
            self.login2App(username: username ?? "", password: password ?? "", encryptedPassword:encryptedPassword!)
        }else {
            LoginDataProvider.getEncrypted(succeedBlock: { (modulus, exponent) in
                let encryptedPassword = RSAHelper.encrypt(password ?? "", modulus: modulus, exponent: exponent)
                self.login2App(username: username ?? "", password: password ?? "", encryptedPassword:encryptedPassword!)
            }) {
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "登录失败", withDescription: "获取加密信息时失败，请稍后重试或联系在线客服。\(getErrorString())", in: self)
                    self._loadView?.removeFromSuperview()
                    NotificationCenter.default.post(name: NSNotification.Name("registLoginfail"), object: nil)
                }
            }
        }
    }
    
    //网络请求登录
    func login2App(username:String,password:String,encryptedPassword:String) -> Void {
        weak var this = self
        NetWorkRequest(API.login(url: "e8a05f5", playername: username, password: encryptedPassword,verifycode:codeString, sessionid: self.sessionid), completion: { (responseData,statusCode,strData) -> (Void) in
            DispatchQueue.main.async {
                let dict =  responseData["data"].dictionaryValue
                let c = dict["c"]?.intValue ?? -1
                let m = dict["m"]?.stringValue ?? ""
                if c == 0 {
                    self._loadView?.removeFromSuperview()
                    
                    let defaults = UserDefaults.standard
                    defaults.set(self.savePasswordButton.isSelected, forKey: DefaultKey.USER_IS_SAVE_PASSWORD)

                    defaults.set(username, forKey: DefaultKey.USER_LOGIN_NAME)
                    if self.savePasswordButton.isSelected {
                        defaults.set(password, forKey: DefaultKey.USER_LOGIN_PASSWORD)
                    }else{
                        defaults.set(nil, forKey: DefaultKey.USER_LOGIN_PASSWORD)
                    }
                    let tokenDict = dict["resultLogin"]?.dictionaryObject
                    let infoDict = dict["resultGetMemberInfo"]?.dictionaryObject
                    GlobalInfo.memberInfoData = infoDict
                    let ccToken =  tokenDict?["cc"] as? String ?? ""
                    let vcToken =  tokenDict?["vc"] as? String ?? ""
                    if(isTest){
                        defaults.set(vcToken, forKey: DefaultKey.VCTOKEN81)
                        defaults.set(ccToken, forKey: DefaultKey.CCTOKEN81)
                    }else{
                        defaults.set(vcToken, forKey: DefaultKey.VCTOKEN11)
                        defaults.set(ccToken, forKey: DefaultKey.CCTOKEN11)
                    }
                    let loginData = strData.data(using: .utf8)
                    defaults.set(loginData, forKey: DefaultKey.LOGIN_DATA)
                    RequestHelper.makeCFCookie()
                    RequestHelper.addTokenCookies()
                    RequestHelper.makeGameDomainCookie()

                    if !defaults.bool(forKey: DefaultKey.USER_IS_SAVE_PASSWORD) {
                        self.passwordTextField.text = ""
                    }
                    UserHelper.setLoginStatus(true)
                    self.performEnterMainPageRequest2True(withLogin: true, dict: dict)
                    
                }else if (c == 1007) {
                      self._loadView?.removeFromSuperview()
                      UIHelper.alertSimpleMessage(about: "登录失败", withDescription: m, in: self)
                }
            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            self._loadView?.removeFromSuperview()
            DispatchQueue.main.async {
                if (reCode == "1000" ) {
                        UIHelper.alertSimpleMessage(about: "登录失败", withDescription: faildInfo, in: self)
                        self._loadView?.removeFromSuperview()
                }else if(reCode == "4848"){
                        RequestHelper.makeGameDomainCookie()
                            this!._loadView?.removeFromSuperview()
                            self.codepophelp.showlgoinCodePopView(title: "请输入验证码", subTitle: " 您的登录密码连续输入错误，请您进行验证", callBack: { (code,sessionid) in
                                this!.codeString = code
                                this!.sessionid = sessionid
                            },superview: this!.view)
                    } else if (reCode == "998" || reCode == "991") {
                        RequestHelper.makeGameDomainCookie()
                            this!._loadView?.removeFromSuperview()
                            let string =  reCode == "998" ? "您的验证码输入有误，请重新输入" : "验证码服务异常 "
                            self.codepophelp.showlgoinCodePopView(title: "请输入验证码", subTitle: (string as NSString) as String, callBack: { (code,sessionid) in
                                this!.codeString = code
                                this!.sessionid = sessionid
//                                this!.buttonLoginClick("")
                            },superview: this!.view)
                    }else {
                       UIHelper.alertSimpleMessage(about: "\(msg)", withDescription: "", in: self)
                      self._loadView?.removeFromSuperview()
                      NotificationCenter.default.post(name: NSNotification.Name("registLoginfail"), object: nil)
                }
            }
        }) { () -> (Void) in

            DispatchQueue.main.async {
                self._loadView?.removeFromSuperview()
                UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
            }
        }
    }
    
//    //网络请求获取密码加密，然后登录
//    func getKeyAndLogin2App(username:String,password:String) -> Void {
//        RequestHelper.get(atPath: "/service/vpkey", withCompletion: { data in
//            let dataArray = try JSONSerialization.jsonObject(with: data, options: []) as? [String: String]
//            let encryptedPassword = RSAHelper.encrypt(password, modulus: dataArray?["modulus"] ?? "", exponent: dataArray?["exponent"] ?? "")
//
//            self.login2App(username: username, password: password, encryptedPassword:encryptedPassword!)
//
//        }, withError: { error in
//            DispatchQueue.main.async {
//                UIHelper.alertSimpleMessage(about: "登录失败", withDescription: "加载信息时发生错误，请稍后重试或联系在线客服。\(getErrorString())", in: self)
//                self._loadView?.removeFromSuperview()
//                NotificationCenter.default.post(name: NSNotification.Name("registLoginfail"), object: nil)
//            }
//        })
//    }
    
    func performEnterMainPageRequest2True(withLogin: Bool = false,dict: [String : JSON]){
        print("已配置gamejson")
        let maintainData: [String:String]? = nil
        let platforms = GlobalInfo.gameInfoData?["platforms"] as? [[String:Any]] ?? [[String:Any]]()
        if GlobalInfo.isMaintain() == true{
            if withLogin {
                DispatchQueue.main.async {
                    UIHelper.alertIsMainTain(about:"系统维护",withDescription:GlobalInfo.gameInfoData?["maintain_msg"] as! String,urlString:GlobalInfo.gameInfoData?["maintain_cs_url"] as! String)
                }
            }
            return
        }
        DispatchQueue.main.async {
         let responseDict = dict["resultGetGameStatus"]?.dictionaryValue
          let responseDataDict =  responseDict?["response"]?.dictionaryValue
          let hallArr = responseDataDict?["data"]?.arrayObject  as? [[String : Any]] ?? [[String : Any]]()
            let memberinfoDict = dict["resultGetMemberInfo"]?.dictionaryObject
            let resultGetInfoDict = dict["resultGetInfo"]?.dictionaryValue
            let resultGetInfoDataDict = resultGetInfoDict?["response"]?.dictionaryObject ?? [String : Any]()
            
            GlobalInfo.memberInfoData = memberinfoDict
            GlobalInfo.siteInfoData = resultGetInfoDataDict
            GlobalInfo.platformInfoData = platforms
            
            GlobalInfo.hallInfoData = hallArr
            GlobalInfo.gameMaintainData = maintainData
            
            // 登录成功 - dimiss 掉登录页
            self.dismiss(animated: true, completion: nil)
            
            //        openAdView()
        }
    }
    
    //获取signkey
    func getSignKey(username: String?, password: String?){
        NetWorkRequest(API.getSignKey(url: "cdb60a1"), completion: { (responseData, statusCode, strData) -> (Void) in
            DispatchQueue.main.async {
                UserDefaults.standard.set(responseData["response"].string ?? "" , forKey: DefaultKey.SIGNKEY)
                UserDefaults.standard.set(true, forKey: DefaultKey.IS_SIGNKEY_STATUS)
                self.actionLogin(username: username, password: password)
            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
                DispatchQueue.main.async {
                    self._loadView?.removeFromSuperview()
                    UIHelper.alertSimpleMessage(about: "", withDescription: "请求数据失败", in: self)
                }
        }) { () -> (Void) in
            DispatchQueue.main.async {
                self._loadView?.removeFromSuperview()
                UIHelper.alertSimpleMessage(about: "", withDescription: "请求数据失败", in: self)
                }
            }
        }
    }

    extension UIDevice {
        //判断是不是 iphonex
        public func isXs() -> Bool {
            if UIScreen.main.bounds.height == 812 {
                return true
            }
            
            return false
        }
}
